<template>
  <div class="search-view">
    <!-- 搜索头部 -->
    <div class="search-header">
      <h1>搜索笔记</h1>
      <div class="search-input-wrapper">
        <el-input
          v-model="searchKeyword"
          size="large"
          placeholder="搜索笔记标题、内容、标签..."
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" :loading="searching">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 搜索结果统计 -->
      <div class="search-stats" v-if="hasSearched">
        <span v-if="searchResults.length > 0">
          找到 <strong>{{ total }}</strong> 条相关笔记
        </span>
        <span v-else>
          未找到相关笔记
        </span>
      </div>
    </div>

    <!-- 高级筛选 -->
    <div class="advanced-filters" v-if="hasSearched">
      <el-row :gutter="20" align="middle">
        <el-col :span="6">
          <el-select v-model="queryParams.type" placeholder="笔记类型" clearable @change="handleSearch">
            <el-option label="全部类型" value="" />
            <el-option label="日常笔记" value="daily" />
            <el-option label="文档笔记" value="document" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="queryParams.categoryId" placeholder="选择分类" clearable @change="handleSearch">
            <el-option label="全部分类" value="" />
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="queryParams.sortBy" placeholder="排序方式" @change="handleSearch">
            <el-option label="相关度" value="relevance" />
            <el-option label="最新发布" value="createTime" />
            <el-option label="最多点赞" value="likeCount" />
            <el-option label="最多收藏" value="favoriteCount" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-col>
      </el-row>
    </div>

    <!-- 热门标签 -->
    <div class="hot-tags" v-if="!hasSearched && hotTags.length > 0">
      <h3>热门标签</h3>
      <div class="tags-list">
        <el-tag
          v-for="tag in hotTags"
          :key="tag.name"
          effect="plain"
          @click="searchByTag(tag.name)"
        >
          {{ tag.name }} ({{ tag.count }})
        </el-tag>
      </div>
    </div>

    <!-- 搜索历史 -->
    <div class="search-history" v-if="!hasSearched && searchHistory.length > 0">
      <h3>搜索历史</h3>
      <div class="history-list">
        <el-tag
          v-for="(keyword, index) in searchHistory"
          :key="index"
          closable
          @click="searchByKeyword(keyword)"
          @close="removeFromHistory(index)"
        >
          {{ keyword }}
        </el-tag>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results" v-if="hasSearched" v-loading="searching">
      <div v-if="searchResults.length === 0 && !searching" class="no-results">
        <el-empty description="没有找到相关笔记">
          <el-button type="primary" @click="clearSearch">重新搜索</el-button>
        </el-empty>
      </div>
      
      <div v-else class="results-list">
        <div 
          v-for="note in searchResults"
          :key="note.id"
          class="result-item"
          @click="goToDetail(note.id)"
        >
          <div class="result-header">
            <h3 class="result-title" v-html="highlightKeyword(note.title)"></h3>
            <div class="result-meta">
              <el-tag v-if="note.type === 'daily'" type="success" size="small">日常笔记</el-tag>
              <el-tag v-if="note.type === 'document'" type="primary" size="small">文档笔记</el-tag>
              <el-tag v-if="note.categoryName" type="info" size="small">{{ note.categoryName }}</el-tag>
              <span class="result-date">{{ formatDate(note.createTime) }}</span>
            </div>
          </div>
          
          <div class="result-content">
            <p class="result-summary" v-html="highlightKeyword(note.summary || note.content?.substring(0, 200) + '...')"></p>
            
            <!-- 匹配的标签 -->
            <div class="matched-tags" v-if="getMatchedTags(note.tags).length > 0">
              <span class="tags-label">匹配标签：</span>
              <el-tag
                v-for="tag in getMatchedTags(note.tags)"
                :key="tag"
                size="small"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
          
          <div class="result-footer">
            <div class="result-author">
              <el-avatar :size="24" :src="note.userAvatar">
                {{ note.userName?.charAt(0) }}
              </el-avatar>
              <span class="author-name">{{ note.userName }}</span>
            </div>
            
            <div class="result-stats">
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ note.viewCount || 0 }}
              </span>
              <span class="stat-item">
                <el-icon><Star /></el-icon>
                {{ note.likeCount || 0 }}
              </span>
              <span class="stat-item">
                <el-icon><Collection /></el-icon>
                {{ note.favoriteCount || 0 }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSearch"
          @current-change="handleSearch"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, View, Star, Collection } from '@element-plus/icons-vue'
import { searchNotes, getNoteCategories, getHotTags } from '@/api/note'
import type { NoteDaily, NoteDocument, NoteCategory, NoteQuery } from '@/types/api'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

// 响应式数据
const searching = ref(false)
const hasSearched = ref(false)
const searchKeyword = ref('')
const searchResults = ref<(NoteDaily | NoteDocument)[]>([])
const categories = ref<NoteCategory[]>([])
const hotTags = ref<{ name: string; count: number }[]>([])
const searchHistory = ref<string[]>([])
const total = ref(0)
const dateRange = ref<[string, string] | null>(null)

// 查询参数
const queryParams = reactive<NoteQuery>({
  pageNum: 1,
  pageSize: 20,
  keyword: '',
  type: '',
  categoryId: '',
  sortBy: 'relevance',
  startDate: '',
  endDate: ''
})

// 执行搜索
const handleSearch = async () => {
  if (!searchKeyword.value.trim() && !queryParams.type && !queryParams.categoryId) {
    ElMessage.warning('请输入搜索关键词或选择筛选条件')
    return
  }
  
  queryParams.keyword = searchKeyword.value.trim()
  queryParams.pageNum = 1
  
  searching.value = true
  hasSearched.value = true
  
  try {
    const response = await searchNotes(queryParams)
    if (response.code === 200) {
      searchResults.value = response.data.rows
      total.value = response.data.total
      
      // 保存搜索历史
      if (queryParams.keyword && !searchHistory.value.includes(queryParams.keyword)) {
        searchHistory.value.unshift(queryParams.keyword)
        if (searchHistory.value.length > 10) {
          searchHistory.value = searchHistory.value.slice(0, 10)
        }
        saveSearchHistory()
      }
    } else {
      ElMessage.error(response.msg || '搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    searching.value = false
  }
}

// 日期范围变化
const handleDateChange = (dates: [string, string] | null) => {
  if (dates) {
    queryParams.startDate = dates[0]
    queryParams.endDate = dates[1]
  } else {
    queryParams.startDate = ''
    queryParams.endDate = ''
  }
  if (hasSearched.value) {
    handleSearch()
  }
}

// 标签搜索
const searchByTag = (tag: string) => {
  searchKeyword.value = tag
  handleSearch()
}

// 关键词搜索
const searchByKeyword = (keyword: string) => {
  searchKeyword.value = keyword
  handleSearch()
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
  hasSearched.value = false
  searchResults.value = []
  queryParams.keyword = ''
  queryParams.type = ''
  queryParams.categoryId = ''
  queryParams.sortBy = 'relevance'
  queryParams.startDate = ''
  queryParams.endDate = ''
  dateRange.value = null
}

// 移除搜索历史
const removeFromHistory = (index: number) => {
  searchHistory.value.splice(index, 1)
  saveSearchHistory()
}

// 保存搜索历史
const saveSearchHistory = () => {
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 加载搜索历史
const loadSearchHistory = () => {
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
}

// 获取分类列表
const getCategoriesList = async () => {
  try {
    const response = await getNoteCategories()
    if (response.code === 200) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取热门标签
const getHotTagsList = async () => {
  try {
    const response = await getHotTags()
    if (response.code === 200) {
      hotTags.value = response.data
    }
  } catch (error) {
    console.error('获取热门标签失败:', error)
  }
}

// 跳转到详情页
const goToDetail = (id: number) => {
  // 这里需要根据搜索结果判断笔记类型，暂时默认跳转到daily类型
  router.push(`/note/daily/${id}`)
}

// 高亮关键词
const highlightKeyword = (text: string) => {
  if (!queryParams.keyword || !text) return text
  
  const regex = new RegExp(`(${queryParams.keyword})`, 'gi')
  return text.replace(regex, '<mark>$1</mark>')
}

// 获取匹配的标签
const getMatchedTags = (tags: string[] = []) => {
  if (!queryParams.keyword) return []
  
  return tags.filter(tag => 
    tag.toLowerCase().includes(queryParams.keyword.toLowerCase())
  )
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 监听路由变化
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword && typeof newKeyword === 'string') {
    searchKeyword.value = newKeyword
    handleSearch()
  }
}, { immediate: true })

// 页面初始化
onMounted(() => {
  loadSearchHistory()
  getCategoriesList()
  getHotTagsList()
  
  // 如果URL中有搜索关键词，自动搜索
  const urlKeyword = route.query.keyword
  if (urlKeyword && typeof urlKeyword === 'string') {
    searchKeyword.value = urlKeyword
    handleSearch()
  }
})
</script>

<style scoped>
.search-view {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.search-header {
  text-align: center;
  margin-bottom: 30px;
}

.search-header h1 {
  font-size: 2.5rem;
  color: #303133;
  margin-bottom: 20px;
}

.search-input-wrapper {
  max-width: 600px;
  margin: 0 auto 20px;
}

.search-stats {
  color: #606266;
  font-size: 1rem;
}

.search-stats strong {
  color: #409eff;
}

.advanced-filters {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.hot-tags,
.search-history {
  margin-bottom: 30px;
}

.hot-tags h3,
.search-history h3 {
  color: #303133;
  margin-bottom: 15px;
}

.tags-list,
.history-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tags-list .el-tag,
.history-list .el-tag {
  cursor: pointer;
}

.search-results {
  min-height: 400px;
}

.no-results {
  text-align: center;
  padding: 60px 0;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.result-item {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.result-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.result-title {
  font-size: 1.3rem;
  color: #303133;
  margin: 0;
  flex: 1;
  margin-right: 15px;
}

.result-title :deep(mark) {
  background: #fff3cd;
  color: #856404;
  padding: 2px 4px;
  border-radius: 3px;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-shrink: 0;
}

.result-date {
  color: #909399;
  font-size: 0.9rem;
}

.result-content {
  margin-bottom: 15px;
}

.result-summary {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 10px;
}

.result-summary :deep(mark) {
  background: #fff3cd;
  color: #856404;
  padding: 2px 4px;
  border-radius: 3px;
}

.matched-tags {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.tags-label {
  color: #909399;
  font-size: 0.9rem;
}

.result-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.result-author {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  color: #606266;
  font-size: 0.9rem;
}

.result-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 0.9rem;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .search-view {
    padding: 10px;
  }
  
  .search-header h1 {
    font-size: 2rem;
  }
  
  .advanced-filters {
    padding: 15px;
  }
  
  .advanced-filters .el-col {
    margin-bottom: 10px;
  }
  
  .result-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .result-meta {
    width: 100%;
    justify-content: space-between;
  }
  
  .result-footer {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .result-stats {
    width: 100%;
    justify-content: space-around;
  }
  
  .matched-tags {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>